package com.basic.library.view;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Toast;

import androidx.fragment.app.DialogFragment;

import com.basic.library.R;

import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;

/**
 * 选择地图
 *
 * @author yys
 */
public class ChooseGuideDialogFragment extends DialogFragment implements OnClickListener {

	private Intent intent;
	private String endAdrs, lat, lng;
	private Activity context;


	public static ChooseGuideDialogFragment getInstance(String lat, String lng, String endAdrs) {
		ChooseGuideDialogFragment newFragment = new ChooseGuideDialogFragment();
		Bundle bundle = new Bundle();
		bundle.putString("lat", lat);
		bundle.putString("lng", lng);
		bundle.putString("endAdrs", endAdrs);
		newFragment.setArguments(bundle);
		return newFragment;
	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Bundle args = getArguments();
		if (args != null) {
			lat = args.getString("lat");
			lng = args.getString("lng");
			endAdrs = args.getString("endAdrs");
		}
	}

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
		getDialog().getWindow().requestFeature(STYLE_NO_TITLE);
		View view = inflater.inflate(R.layout.base_fragment_choose_guide, container);
		view.findViewById(R.id.tv_baidu).setOnClickListener(this);
		view.findViewById(R.id.tv_gaode).setOnClickListener(this);
		context = getActivity();
		return view;
	}


	@Override
	public void onClick(View v) {
		int i = v.getId();
		if (i == R.id.tv_baidu) {
			gotoBaiduGuide();

		} else if (i == R.id.tv_gaode) {
			gotoAMapGuide();

		}
		ChooseGuideDialogFragment.this.dismiss();
	}


	private void gotoAMapGuide() {
		if (isAvilible(context, "com.autonavi.minimap")) {
			try {
				Intent intent = new Intent("android.intent.action.VIEW", Uri.parse("androidamap://navi?sourceApplication=数字工场&lat=" + lat + "&lon=" + lng + "&dev=0"));
				intent.setPackage("com.autonavi.minimap");
				context.startActivity(intent);
			} catch (Exception e) {
				gotoWebGuide(0);
			}
		} else {
			gotoWebGuide(0);
		}
	}

	private void gotoWebGuide(int type) {

		if (type == 0) {
			Toast.makeText(context, "您尚未安装高德地图", Toast.LENGTH_LONG).show();
			Uri uri = Uri.parse("market://details?id=com.autonavi.minimap");
			Intent intent = new Intent(Intent.ACTION_VIEW, uri);
			context.startActivity(intent);
		} else if (type == 1) {
			Toast.makeText(context, "您尚未安装百度地图", Toast.LENGTH_LONG).show();
			Uri uri = Uri.parse("market://details?id=com.baidu.BaiduMap");
			Intent intent = new Intent(Intent.ACTION_VIEW, uri);
			context.startActivity(intent);
		}

//		new androidx.appcompat.app.AlertDialog.Builder(getActivity())
//				.setTitle("提示")
//				.setMessage("您未安装该地图App或版本过低，调起网页导航？")
//				.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//					@Override
//					public void onClick(DialogInterface dialog, int which) {
//						Intent intent = new Intent();
//						intent.setAction("android.intent.action.VIEW");
//						String url = "http://m.amap.com/?from="+ BaseConstants.myLat+","+ BaseConstants.myLng+"(from)&to="+ lat+","+ lng +"(to)";
//						System.out.println("----->"+url);
//						Uri content_url = Uri.parse(url);
//						intent.setData(content_url);
//						context.startActivity(intent);
//					}
//				})
//				.setNegativeButton("取消",null).show();

	}

	@SuppressWarnings("deprecation")
	private void gotoBaiduGuide() {
		if (isAvilible(context, "com.baidu.BaiduMap")) {
			try {
				intent = Intent.getIntent("intent://map/direction?" +
						//"origin=latlng:"+"34.264642646862,108.95108518068&" +   //起点  此处不传值默认选择当前位置
						"destination=latlng:" + lat + "," + lng + "|name:我的目的地" +        //终点
						"&mode=driving&" +          //导航路线方式
//                     "region=北京" +           //
						"&src=" + endAdrs + "#Intent;scheme=bdapp;package=com.baidu.BaiduMap;end");
				context.startActivity(intent); //启动调用
			} catch (URISyntaxException e) {
				Log.e("intent", e.getMessage());
				gotoWebGuide(1);
			}
		} else {
			gotoWebGuide(1);
		}
	}

	@Override
	public void onStart() {
		super.onStart();
	}

	public static boolean isAvilible(Context context, String packageName) {
		//获取packagemanager
		final PackageManager packageManager = context.getPackageManager();
		//获取所有已安装程序的包信息
		List<PackageInfo> packageInfos = packageManager.getInstalledPackages(0);
		//用于存储所有已安装程序的包名
		List<String> packageNames = new ArrayList<>();
		//从pinfo中将包名字逐一取出，压入pName list中
		if (packageInfos != null) {
			for (int i = 0; i < packageInfos.size(); i++) {
				String packName = packageInfos.get(i).packageName;
				packageNames.add(packName);
			}
		}
		//判断packageNames中是否有目标程序的包名，有TRUE，没有FALSE
		return packageNames.contains(packageName);
	}

}
